﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class Login : WebPageBase
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.QueryString["LogOut"] != null)
            {
                Session["User" + Session.SessionID] = null;
                Response.Cookies["RFriend_Email"].Value = null;
                Response.Cookies["RFriend_UID"].Value = null;
                Response.Cookies["RFriend_PWD"].Value = null;
                Session.Abandon();
                System.Web.Security.FormsAuthentication.SignOut();
                Response.Redirect("Login.aspx");
            }

            if (Request["error"] != null)
            {
                Message1.Mensaje = Request["error"].ToString();
                Message1.Tipo = Constant.MESSAGE_ERROR;
            }
            if (Request["msj"] != null)
            {
                Message1.Mensaje = Request["msj"].ToString();
                Message1.Tipo = Constant.MESSAGE_OK;
            }

            if (Response.Cookies["RFriend_Email"] != null)
            {
                ctlLogin.UserName = Response.Cookies["RFriend_Email"].Value;
                ctlLogin.RememberMeSet = true;
            }
            Button lbButton = ctlLogin.FindControl("LoginButton") as Button;
            ctlLogin.Focus();
            Form.DefaultButton = lbButton.UniqueID;
        }
    }
    protected void OnAuthenticate(object sender, AuthenticateEventArgs e)
    {
        bool Authenticated = false;
        CheckBox chBox = (CheckBox)ctlLogin.FindControl("RememberMe");
        Authenticated = UserAuthenticate(ctlLogin.UserName, ctlLogin.Password);

        e.Authenticated = Authenticated;
        if (Authenticated == true)
        {
            if (chBox.Checked == true)
            {
                Response.Cookies["RFriend_Email"].Value = ctlLogin.UserName;
                Response.Cookies["RFriend_PWD"].Value = ctlLogin.Password;
                Response.Cookies["RFriend_UID"].Value = base.UserSystem.Id.ToString();
                Response.Cookies["RFriend_Email"].Expires = DateTime.Now.AddMonths(3);
                Response.Cookies["RFriend_PWD"].Expires = DateTime.Now.AddMonths(3);
                Response.Cookies["RFriend_UID"].Expires = DateTime.Now.AddMonths(3);
            }
            Response.Redirect("Home.aspx");
        }
    }

    private bool UserAuthenticate(string UserName, string Password)
    {
        bool boolReturnValue = false;

        if (db.UserQs.Any(u => u.Email.Equals(UserName) && u.Password.Equals(Password)))
        {
            var userVar = from u in db.UserQs
                          where u.Email.Equals(UserName)
                          where u.Password.Equals(Password)
                          select new { u.Id, u.RoleId };

            UserQ user = null;

            foreach (var u in userVar)
            {
                user = new UserQ();
                user.Id = u.Id;
                user.RoleId = u.RoleId;
            }

            if (user != null)
            {
                if (user.RoleId == -1)
                {
                    boolReturnValue = false;
                    Message1.Mensaje = "El usuario aun no ha sido dado de Alta. Por favor espera la llamada de nuestros asesores para confirmar sus datos. Gracias.";
                    Message1.Tipo = Constant.MESSAGE_ERROR;
                }
                else
                {
                    boolReturnValue = true;
                    UserSystem = db.UserQs.First(us => us.Id.Equals(user.Id));
                    user.LastLogin = System.DateTime.Now;
                    db.SubmitChanges();
                }
            }
            else
            {
                if (db.UserQs.Any(u => u.Email.Equals(UserName) && u.Password.Equals(Password) && u.RoleId != 5 && u.RoleId != -1))
                {
                    user = db.UserQs.First(u => u.Email.Equals(UserName) && u.Password.Equals(Password) && u.RoleId != 5 && u.RoleId != -1);
                    boolReturnValue = true;
                    UserSystem = user;
                    user.LastLogin = System.DateTime.Now;
                    db.SubmitChanges();
                }
                else
                {
                    boolReturnValue = false;
                    Message1.Mensaje = "El usuario no existe.";
                    Message1.Tipo = Constant.MESSAGE_ERROR;
                }
            }

        }
        return boolReturnValue;

    }

}
